package com.fauks.ssm.spring.tx_annotation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class BookDaoImpl implements IBookDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Integer selectBookPriceById(int id) {
        String sql = "SELECT price FROM t_book WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, Integer.class, id);
    }

    @Override
    public void updateBookStock(int id) {
        //查询库存
        String sql = "SELECT stock FROM t_book WHERE id = ?";
        Integer stock = jdbcTemplate.queryForObject(sql, Integer.class, id);
        if (stock <= 0) {
            throw new RuntimeException("库存不足...");
        }

        sql = "UPDATE t_book SET stock = stock-1 WHERE id = ?";
        jdbcTemplate.update(sql, id);
    }

    @Override
    public void updateAccount(String username, int price) {
        //查询余额
        String sql = "SELECT account FROM t_account WHERE username =?";
        Integer account = jdbcTemplate.queryForObject(sql, Integer.class, username);
        if (account < price) {
            throw new RuntimeException("余额不足...");
        }

        sql = "UPDATE t_account SET account =account-? WHERE username = ?";
        jdbcTemplate.update(sql, price, username);
    }
}
